#include <func.h>

// 临界区：对共享资源的访问

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  // 默认属性

void* start_routine(void* arg) 
{
    long long* value = (long long*) arg;
    for(int i = 0; i < 10000000; i++) {
        // 上锁
        pthread_mutex_lock(&mutex);
        (*value)++;
        // 释放锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main(int argc, char* argv[])
{
    long long* value = (long long*)calloc(1, sizeof(long long));
    // 创建两个线程
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, start_routine, (void*)value);
    pthread_create(&tid2, NULL, start_routine, (void*)value);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    printf("value = %lld\n", *value);
    free(value);

    return 0;
}

